package com.fx.zmlzml.controller;

import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcCpu;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcCpuService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑CPU Controller
 * 提供RESTful API接口，用于操作电脑CPU数据
 */
@RestController
@RequestMapping("/api/cpu")
@Tag(name = "电脑CPU管理", description = "提供电脑CPU的CRUD操作及相关查询功能")
public class PcCpuController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcCpuController.class);
    
    @Autowired
    private PcCpuService pcCpuService;
    
    /**
     * 分页获取电脑CPU列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页获取电脑CPU列表", description = "分页查询系统中的电脑CPU信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcCpu>> getPcCpusByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑CPU列表请求，页码：{}，每页条数：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum <= 0 || pageSize <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "页码和每页条数必须为正整数");
            }
            
            // 使用PageHelper进行分页
            PageHelper.startPage(pageNum, pageSize);
            List<PcCpu> list = pcCpuService.list();
            PageInfo<PcCpu> pageInfo = new PageInfo<>(list);
            
            logger.debug("分页查询电脑CPU成功，总条数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "cpu.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("分页查询电脑CPU失败，页码：{}，每页条数：{}", pageNum, pageSize, e);
            return Result.i18nError(ErrorEnum.CPU_QUERY_FAILED.getCode(), 
                    "cpu.query.fail", null);
        }
    }
    
    /**
     * 根据ID获取电脑CPU详情
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取电脑CPU详情", description = "根据唯一标识符查询电脑CPU的详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcCpu> getPcCpuById(
            @Parameter(description = "CPU ID", example = "1", required = true) @PathVariable Long id) {
        logger.info("查询电脑CPU详情请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        MessageUtils.getMessage("common.validation.id"));
            }
            
            PcCpu cpu = pcCpuService.getById(id);
            if (cpu == null) {
                logger.warn("未找到电脑CPU，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND,
                        MessageUtils.getMessage("cpu.not_found"));
            }
            logger.debug("查询电脑CPU详情成功，ID：{}", id);
            return Result.i18nSuccess(cpu, "cpu.query.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("查询电脑CPU详情失败，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.CPU_QUERY_FAILED.getCode(), 
                    "cpu.query.fail", null);
        }
    }
    
    /**
     * 添加电脑CPU
     */
    @PostMapping
    @Operation(summary = "添加电脑CPU", description = "向系统中添加新的电脑CPU信息")
    @ApiResponses({
            @ApiResponse(responseCode = "201", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcCpu> addPcCpu(
            @Parameter(description = "电脑CPU信息", required = true) @RequestBody PcCpu pcCpu) {
        logger.info("添加电脑CPU请求，型号：{}", pcCpu.getModel());
        try {
            // 参数校验
            if (pcCpu == null) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "电脑CPU信息不能为空");
            }
            if (pcCpu.getModel() == null || pcCpu.getModel().trim().isEmpty()) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "CPU型号不能为空");
            }
            if (pcCpu.getManufacturer() == null || pcCpu.getManufacturer().trim().isEmpty()) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "CPU制造商不能为空");
            }
            
            // 设置创建时间和更新时间
            pcCpu.setCreatedTime(new Date());
            pcCpu.setUpdatedTime(new Date());
            
            boolean result = pcCpuService.save(pcCpu);
            if (!result) {
                logger.warn("添加电脑CPU失败，型号：{}", pcCpu.getModel());
                throw new BusinessException(ErrorEnum.CPU_ADD_FAILED, 
                        "添加电脑CPU失败");
            }
            logger.debug("添加电脑CPU成功，ID：{}", pcCpu.getId());
            return Result.i18nSuccess(pcCpu, "cpu.add.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("添加电脑CPU失败，型号：{}", pcCpu != null ? pcCpu.getModel() : "未知", e);
            return Result.i18nError(ErrorEnum.CPU_ADD_FAILED.getCode(), 
                    "cpu.add.fail", null);
        }
    }
    
    /**
     * 更新电脑CPU信息
     */
    @PutMapping("/{id}")
    @Operation(summary = "更新电脑CPU信息", description = "更新系统中已存在的电脑CPU信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcCpu> updatePcCpu(
            @Parameter(description = "CPU ID", example = "1", required = true) @PathVariable Integer id,
            @Parameter(description = "电脑CPU信息", required = true) @RequestBody PcCpu pcCpu) {
        logger.info("更新电脑CPU请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "CPU ID必须为正整数");
            }
            if (pcCpu == null) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "电脑CPU信息不能为空");
            }
            
            // 检查CPU是否存在
            PcCpu existingCpu = pcCpuService.getById(id);
            if (existingCpu == null) {
                logger.warn("未找到电脑CPU，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND, 
                        "未找到指定的电脑CPU");
            }
            
            // 设置ID和更新时间
            pcCpu.setId(id);
            pcCpu.setUpdatedTime(new Date());
            
            boolean result = pcCpuService.updateById(pcCpu);
            if (!result) {
                logger.warn("更新电脑CPU失败，ID：{}", id);
                throw new BusinessException(ErrorEnum.CPU_UPDATE_FAILED, 
                        "更新电脑CPU失败");
            }
            logger.debug("更新电脑CPU成功，ID：{}", id);
            return Result.i18nSuccess(pcCpu, "cpu.update.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑CPU失败，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.CPU_UPDATE_FAILED.getCode(), 
                    "cpu.update.fail", null);
        }
    }
    
    /**
     * 删除电脑CPU
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑CPU", description = "从系统中删除指定的电脑CPU信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "400", description = "参数无效", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Void> deletePcCpu(
            @Parameter(description = "CPU ID", example = "1", required = true) @PathVariable Long id) {
        logger.info("删除电脑CPU请求，ID：{}", id);
        try {
            // 参数校验
            if (id == null || id <= 0) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID, 
                        "CPU ID必须为正整数");
            }
            
            // 检查CPU是否存在
            PcCpu existingCpu = pcCpuService.getById(id);
            if (existingCpu == null) {
                logger.warn("未找到电脑CPU，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND, 
                        "未找到指定的电脑CPU");
            }
            
            boolean result = pcCpuService.removeById(id);
            if (!result) {
                logger.warn("删除电脑CPU失败，ID：{}", id);
                throw new BusinessException(ErrorEnum.CPU_DELETE_FAILED, 
                        "删除电脑CPU失败");
            }
            logger.debug("删除电脑CPU成功，ID：{}", id);
            return Result.i18nSuccess(null, "cpu.delete.success", null);
        } catch (BusinessException e) {
            // 业务异常已记录日志，直接返回
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑CPU失败，ID：{}", id, e);
            return Result.i18nError(ErrorEnum.CPU_DELETE_FAILED.getCode(), 
                    "cpu.delete.fail", null);
        }
    }
}